<?php

declare(strict_types=1);

namespace app\core;

class Config
{
    private static $config = [];
    public static function init(){
       
        $files=glob(CONF.'/*.php');
       $fileList=[];
        foreach($files as $v){
           
            
            $file=preg_replace('/.php/', '', $v);
            $last=array_reverse(explode('/',$file))[0];
            // echo $v."\r\n";
            $fileList[$last] =  include $v;
        }
        // print_r($fileList);
        self::$config=$fileList;
    }
    public static function load(string $name)
    {
        // self::set($name);

        return self::get($name);
    }
    public static function get(string $name = null, $default = null)
    {


        if (false === strpos($name, '.')) {
            return self::pull($name);
        }

        $name    = explode('.', $name);
        $name[0] = strtolower($name[0]);
        $config  = self::$config;

        // 按.拆分成多维数组进行判断
        foreach ($name as $val) {
            if (isset($config[$val])) {
                $config = $config[$val];
            } else {
                return $default;
            }
        }

        return $config;
    }
    private static function pull(string $name): array
    {
        $name = strtolower($name);

        return self::$config[$name] ?? [];
    }
    private static function set(string $name)
    {



        $name    = explode('.', $name);
        $name[0] = strtolower($name[0]);
        $file = $name[0];
        $config = self::$config;
        if (!array_key_exists($file, $config)) {

            $path = CONF . '/' . $file . '.php';
            // self::$config[$file] =  include $path;
            $file=preg_replace('/.php/', '', $path);
            $last=array_reverse(explode('/',$file))[0];
            // echo $v."\r\n";
            $fileList[$last] =  include $path;
        }
    }
}
